package com.beijiteshop.shop.ui.order.fragment

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import com.beijiteshop.libcommon.ext.databinding.bindView
import com.beijiteshop.libcommon.utils.EventUtil
import com.beijiteshop.shop.R
import com.beijiteshop.shop.app.PageIndex
import com.beijiteshop.shop.base.BaseContainerFragment
import com.beijiteshop.shop.databinding.FragmentOrderConfirmBinding
import com.beijiteshop.shop.model.api.request.OrderRequest
import com.beijiteshop.shop.model.api.response.*
import com.beijiteshop.shop.model.entity.CheckBoxEntity
import com.beijiteshop.shop.model.event.EventKey
import com.beijiteshop.shop.ui.address.fragment.AddressFragment
import com.beijiteshop.shop.ui.order.vm.OrderVM
import com.beijiteshop.shop.utils.twoDecimal
import com.blankj.utilcode.util.LogUtils
import org.koin.android.viewmodel.ext.android.viewModel
import java.lang.StringBuilder

/**
 * @author LiaoZhongKai
 * @Date 2021/3/8 16:15
 * @Description 订单确认页面
 */
class OrderConfirmFragment : BaseContainerFragment(R.layout.fragment_order_confirm) {

    companion object{
        const val BUNDLE_PRODUCT = "bundle_product"

        fun newInstance(productBean: ProductBean): Fragment{
            return OrderConfirmFragment().apply {
                val bundle = Bundle()
                bundle.putParcelable(BUNDLE_PRODUCT,productBean)
                arguments = bundle
            }
        }
    }

    private val mBinding: FragmentOrderConfirmBinding by bindView()
    private val mOrderVM: OrderVM by viewModel()
    private var mProductBean: ProductBean? = null
    private var mOrderConfirmBean: OrderConfirmBean? = null
    //优惠券列表
    private var mCouponList: MutableList<CheckBoxEntity<Coupon>>? = null
    //当前选择的优惠券，如果有优惠券则默认第一个，没有默认null
    private var mSelectCoupon: Coupon? = null

    private val mCouponSelectDialog: CouponSelectDialog by lazy {
        CouponSelectDialog()
    }

    override fun onLazyLoad() {
        requestData()
    }

    override fun initView(view: View) {
        mProductBean = arguments?.getParcelable(BUNDLE_PRODUCT)
        mBinding.includeTitleBar.titleBarTitleTv.text = resources.getString(R.string.order_info_confirm)
        initProductInfo()
    }

    override fun initData() {
    }

    override fun initEvent() {
        //返回按钮
        mBinding.includeTitleBar.titleBarBackIv.setOnClickListener {
            close()
        }

        //地址
        mBinding.orderConfirmArrowIv.setOnClickListener {
            startActivity(PageIndex.ADDRESS,Bundle().apply {
                putBoolean(AddressFragment.BUNDLE_IS_SELECT,true)
            })
        }

        //优惠券
        mBinding.orderConfirmCouponNumTv.setOnClickListener {
            if (!mCouponList.isNullOrEmpty()){
                mCouponSelectDialog.show(childFragmentManager,mCouponList!!)
            }
        }

        //优惠券选择框
        mCouponSelectDialog.setOnSelectListener(object : CouponSelectDialog.IOnSelectListener{
            override fun onSelect(position: Int,coupon: Coupon) {
                setCouponDiscountPrice(coupon.couponValue)
                updateCouponItem(position)
                updateNeedPayPrice(coupon)
            }
        })

        //提交订单
        mBinding.orderConfirmSubmitBtn.setOnClickListener {
            commitOrder()
        }

        startObserve()
    }

    /**
     * 获取订单信息
     */
    private fun requestData(){
        mProductBean?.let {
            mOrderVM.getOrderConfirmInfo(it.bus_GoodsID)
        }
    }

    private fun initProductInfo(){
        mProductBean?.let {
            mBinding.product = it
        }
        mProductBean?.let {
            val result = StringBuilder()
            if (!it.spec.isNullOrEmpty()){
                result.append(it.spec)
            }
            if (!it.color.isNullOrEmpty()){
                result.append(" ")
                result.append(it.color)
            }
            mBinding.orderConfirmProductDescTv.text = result
        }
    }

    private fun startObserve(){

        mOrderVM.apply {
            liveOrderConfirm.observeKt {bean ->
                hideLoading()
                mOrderConfirmBean = bean
                bean?.also {
                    //是否售罄
                    mBinding.good = it.good

                    //默认地址
                    if (it.address != null){
                        mBinding.address = it.address
                    }else{
                        mBinding.orderConfirmAddressTv.text = resources.getString(R.string.please_select_address)
                    }

                    //订单信息
                    mBinding.order = it

                    //优惠券数量、价格
                    if (!it._coupon.isNullOrEmpty()){
                        setCouponNum(it._coupon!!.size)
                        setCouponDiscountPrice(it._coupon!![0].couponValue)
                        setCouponList(it._coupon!!)
                        updateNeedPayPrice(it._coupon!![0])
                    }else{
                        setCouponNum(0)
                        setCouponDiscountPrice(0f)
                        setNeedPay(it.needpay)
                    }
                }
            }

            liveCommitOrder.observeKt {orderNum ->
                hideLoading()
                if (!orderNum.isNullOrEmpty()){
                    startActivity(PageIndex.ORDER_PAY,Bundle().apply {
                        putString(OrderPayFragment.BUNDLE_ORDER_NUMBER,orderNum)
                    })
                    //通知购物车刷新
                    EventUtil.post(EventKey.REFRESH_SHOP_CART)
                    close()
                }
            }

            liveError.observeKt {
                hideLoading()
                showToast(it?:resources.getString(R.string.something_error))
            }

            liveNetError.observeKt {msg->
                hideLoading()
                msg?.let {
                    showToast(it)
                }
            }
        }

        //接收地址更改的事件
        EventUtil.observe<AddressBean?>(this,EventKey.ORDER_ADDRESS){ address ->
            address?.let {
                mBinding.address = it
                mOrderConfirmBean?.address = it
            }
        }
    }

    /**
     * 设置优惠券数量
     */
    private fun setCouponNum(num: Int){
        val strFormat = resources.getString(R.string.coupon_num)
        mBinding.orderConfirmCouponNumTv.text = String.format(strFormat,num)
    }

    /**
     * 设置选中的优惠券优惠价格
     */
    private fun setCouponDiscountPrice(value: Float){
        val strFormat = resources.getString(R.string.negative_price_format)
        mBinding.orderConfirmCouponPriceTv.text = String.format(strFormat, value)
    }

    /**
     * 设置优惠券列表
     */
    private fun setCouponList(coupons: List<Coupon>){
        mCouponList = mutableListOf()
        coupons.forEachIndexed { index, coupon ->
            mCouponList!!.add(CheckBoxEntity(index == 0,coupon))
        }
    }

    /**
     * 更新某个优惠券
     */
    private fun updateCouponItem(position: Int){
        if (mCouponList!= null){
            mCouponList!!.forEachIndexed { index, checkBoxEntity ->
                checkBoxEntity.isSelected = index == position
            }
        }
    }

    /**
     * 选择优惠券后更新应付价格
     * @param couponValue 优惠券金额
     */
    private fun updateNeedPayPrice(coupon: Coupon){
        mSelectCoupon = coupon
        mOrderConfirmBean?.let {
            Log.d("TAG","needPay:${it.needpay.toFloat()} coupon:${coupon.couponValue} total:${(it.needpay.toFloat()-coupon.couponValue).twoDecimal()}")
            it.needpay.toFloat()
            mBinding.orderConfirmPriceTv.text = (it.needpay.toFloat() - coupon.couponValue).twoDecimal().toString()
        }
    }

    /**
     * 设置应付价格
     */
    private fun setNeedPay(price: String){
        mBinding.orderConfirmPriceTv.text = price
    }

    /**
     * 提交订单
     */
    private fun commitOrder(){
        mOrderConfirmBean?.let {

            if (it.address == null){
                showToastInCenter(resources.getString(R.string.please_select_address))
            }else{
                showLoading(resources.getString(R.string.committing))
                val remark = mBinding.orderConfirmProductRemarksEt.text.toString()
                val orderRequest = OrderRequest(
                    it.address!!.bus_AddressID,
                    mSelectCoupon?.bus_Coupon_UserID,
                    it.good.bus_GoodsID,
                    mProductBean?.color?:"",
                    mSelectCoupon?.couponValue?:0f,
                    mProductBean?.spec?:"",
                    it.postage.toFloat(),
                    remark
                )
                mOrderVM.commitOrder(orderRequest)
            }
        }
    }
}